package com.hhdys.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hhdys.constant.Env;
import com.hhdys.message.AbstractMessageDelivery;
import com.hhdys.message.MessageResult;
import com.hhdys.utils.HttpHelper;

/**
 * 发送消息 errorCode： 40001 获取access_token时Secret错误，或者access_token无效 40014
 * 不合法的access_token 41001 缺少access_token 42001 access_token超时；
 * 
 * @author hhdys
 *
 */
public class MsgService {

	private static final Logger log = LogManager.getLogger(MsgService.class);

	public static boolean sendMessage(AbstractMessageDelivery delivery) {
		String url = String.format(Env.qiyeMessageUrl, TokenService.getAccessToken());
		JSONObject result = HttpHelper.httpPost(url, delivery);
		String deliveryStr = JSON.toJSONString(delivery);
		log.info("delivery is :{}", deliveryStr);
		if (result == null) {
			log.error("send message error:url:{},delivery:{}", url, deliveryStr);
			return false;
		}

		MessageResult messageResult = JSONObject.toJavaObject(result, MessageResult.class);
		int errorCode = messageResult.getErrcode();
		if (errorCode == 0) {
			return true;
		}
		// 失败
		if (errorCode == 40001 || errorCode == 40014 || errorCode == 41001) {
			log.info("token is valid!!!errorCode:{}", errorCode);
			TokenService.setTokenInvalid();
			boolean reTryResult = false;
			for (int i = 0; i < 3; i++) {// 重试三次
				reTryResult = sendMessage(delivery);
				if (reTryResult) {
					log.info("retry {} times success!", i);
					break;
				}
			}
			if (!reTryResult) {
				log.error("retry failed!!!delivery is:{}", deliveryStr);
			}
		}
		log.error("send message error!!! errorCode is:{},url:{},delivery is:{}", errorCode, url, deliveryStr);
		return false;

	}

}
